package cn.yj.common.lock.redis;

import cn.yj.common.JedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

/**
 * 给锁续约看门狗
 *
 * @author 永健
 * @since 2022-01-26 13:58
 */
public class KeyWatchdogTask extends TimerTask {
    private static final Logger log = LoggerFactory.getLogger(KeyWatchdogTask.class);

    /**
     * 监听的Key
     */
    private String key;
    private String value;

    /**
     * 将key续约为 seconds
     */
    private int seconds;

    /**
     * 多少秒执行一次检测
     */
    private int delayWatchDog;

    private static final Integer RESULT_SUCCESS = 1;

    public KeyWatchdogTask(String key,String value, int seconds, int delayWatchDog) {
        this.key = key;
        this.value = value;
        this.seconds = seconds;
        this.delayWatchDog = delayWatchDog;
    }

    @Override
    public void run() {
        Jedis nJedis = JedisUtils.getJedis();
        try {
            while (true) {
                try {
                    Thread.sleep(delayWatchDog * 1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                String script =
                        "if redis.call('exists', KEYS[1]) == 1 then "+
                                "if redis.call('get', KEYS[1]) == KEYS[2] then "+
                                    "redis.call('pexpire',KEYS[1], KEYS[3]); "+
                                    "return 1; "+
                                "else "+
                                   "return -1;"+
                                "end; "+
                        "else "+
                            "return -1;"+
                        "end; ";
                List<String> keys = new ArrayList<>();
                keys.add(this.key);
                keys.add(this.value);
                keys.add(String.valueOf(this.seconds));
                Object eval = nJedis.eval(script, 3,this.key,this.value,String.valueOf(this.seconds*1000));
                if (!RESULT_SUCCESS.equals(Integer.parseInt(eval.toString()))){
                    break;
                }
            }
        } finally {
            nJedis.close();
        }
    }
}
